#include <string.h>
#include <iostream>
using std::cout;
using std::endl;

class Computer{
public:
    Computer(const char * brand,double price)
        : _brand(new char[strlen(brand) + 1]())
          , _price(price)
    {
        strcpy(_brand,brand);
        _totalPrice += _price;
        cout << "Computer(const char *,double)" << endl;
    }

    Computer(const Computer & rhs)
        : _brand(new char[strlen(rhs._brand) + 1]())
          , _price(rhs._price)
    {
        strcpy(_brand,rhs._brand);
        _totalPrice += _price;
        cout << "Computer(const Computer &)" << endl;
    }

    Computer & operator=(const Computer & rhs){
        if(this != &rhs){//1.考虑自复制问题
            delete [] _brand;//2.回收左操作数原本申请的堆空间
            _totalPrice -= _price;
            _brand = new char[strlen(rhs._brand) + 1]();//3.深拷贝(复制)
            strcpy(_brand,rhs._brand);
            _price = rhs._price;
            _totalPrice += _price;
            cout << "Computer & operator=" << endl;

        }
        return *this;//4.返回*this
    }

    void print(){
        cout << "brand:" << _brand << endl
            << "price:" << _price << endl
            << "totalPrice:" << _totalPrice << endl;
    }

    ~Computer(){
        if(_brand){
            delete [] _brand;
            _brand = nullptr;
            _totalPrice -= _price;
        }
        cout << "~Computer()" << endl;
    }
private:
    char * _brand;
    double _price;
    //数据成员的类型前面加上static关键字
    //表示这是一个static成员（共享）
    static double _totalPrice;
};
double Computer::_totalPrice = 0;
//
//1.private的静态数据成员无法在类之外直接访问
//2.对于静态数据成员的初始化，必须放在类外（一般紧接类的定义）
//这是规则1的特殊情况
//3.静态数据成员初始化时不能在前面加static
//4.如果有多条静态数据成员，那么它们的初始化顺序需要与声明顺序一致

Computer pc0("C",4000);
void test0(){
    Computer pc("A",3000);
    Computer pc2("B",5000);
    pc.print();
    cout << endl;
    pc = pc2;
    pc.print();
}

//静态数据成员存在全局静态区，不在对象的内存布局中
void test1(){
    cout << sizeof(Computer) << endl;
}

int main(void){
    /* test0(); */
    /* pc0.print(); */
    test1();
    return 0;
}
